﻿using NetDh.Lib;
using NetDh.Lib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;

namespace NetDh.Presentation.Common
{
    /*此类无用。和mvc类似，统一使用自定义的ActionFilterAttribute，更灵活*/
    public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            //当Action标记为可匿名访问[AllowAnonymous]时，是不会进入此函数。因此IdentityHttpContext.Current等处理要在OnAuthorization
            //return IdentityHttpContext.Current.Token != null;
            return base.IsAuthorized(actionContext);
            #region //源码解析 System.Web.Http.AuthorizeAttribute
            //public override void OnAuthorization(HttpActionContext actionContext)
            //{
            //    if (actionContext == null)
            //    {
            //        throw Error.ArgumentNull("actionContext");
            //    }
            //-->//paul 如果有[AllowAnonymous]标记，则这边就退出，不会执行以下的IsAuthorized
            //    if (AuthorizeAttribute.SkipAuthorization(actionContext))
            //    {
            //        return;
            //    }
            //    if (!this.IsAuthorized(actionContext))
            //    {
            //        this.HandleUnauthorizedRequest(actionContext);
            //    }
            //}
            #endregion
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //IdentityHttpContext.Current.Clear();
            //var ticket = actionContext.Request.GetHeaderValue("token");
            //var token = TokenHelper.GetToken(ticket);
            //IdentityHttpContext.Current.Token = token;
            //actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "---RequestNotAuthorized");//SRResources.RequestNotAuthorized-->"RequestNotAuthorized"
            ////赋值两次肯定是以最新一次为准
            //actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "22---RequestNotAuthorized");
            base.OnAuthorization(actionContext);
        }
    }
}
